import django_filters
from django.db.models import Q
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from user.models import GoodsModel, UserModel, BannerModel, ShopModel
from user.serializers import RegisterSerializer, GoodsSerializer, BannersSerializer, ShopModelSerializer
from user.xx import get_tool_agent


# 注册视图
class RegisterAPIView(APIView):
    def post(self, request, *args, **kwargs):
        value = request.data.get('username')
        if UserModel.objects.filter(Q(username=value) | Q(email=value) | Q(phone=value)).exists():
            return Response({'code': 400, 'msg': '用户名或邮箱或手机号已存在'})
        data = request.data
        print(data)
        ser = RegisterSerializer(data=data)
        print('----------------')
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '注册成功'})
        else:
            return Response({'code': 400, 'msg': '注册失败', 'data': ser.errors})


# 历史记录视图
messages = []


class HistoryChainAPIView(APIView):
    def get(self, request):
        user_input = request.query_params.get('user_input', None)
        if user_input is not None:
            res = get_tool_agent(user_input)
            messages.append(res)
            return Response(messages)


# 分页配置
class PageC(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'


# 商品过滤器
class GoodsDetails(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name='name', lookup_expr="contains")
    price = django_filters.NumberFilter(field_name='price', lookup_expr='gte')  # 大于等于
    stock = django_filters.NumberFilter(field_name='stock', lookup_expr='lte')  # 小于等于

    class Meta:
        model = GoodsModel
        fields = ['name', 'price', 'stock']


# 商品展示视图
class GoodsShowAPIView(ListAPIView):
    queryset = GoodsModel.objects.all().order_by('id')
    serializer_class = GoodsSerializer
    pagination_class = PageC
    filter_backends = [DjangoFilterBackend]
    filterset_class = GoodsDetails

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class GoodsModelViewSet(ModelViewSet):
    queryset = GoodsModel.objects.all().order_by('id')
    serializer_class = GoodsSerializer
    pagination_class = PageC
    filter_backends = [DjangoFilterBackend]
    filterset_class = GoodsDetails


class BannersAPIView(ListAPIView):
    queryset = BannerModel.objects.all()[:10]
    serializer_class = BannersSerializer


class ShopListAPIView(ListAPIView):
    queryset = ShopModel.objects.all()
    serializer_class = ShopModelSerializer

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response({'code': 200, 'msg': '获取成功', 'data': serializer.data})

    def post(self, request, *args, **kwargs):
        data = request.data.get('id')
        print(data)
        good = GoodsModel.objects.filter(id=data).first()
        shop = ShopModel.objects.filter(name=good.name).first()
        if not good:
            shop_x = ShopModel.objects.create(
                name=good.name,
                price=good.price,
                stock=1,
                image=good.image,
                description=good.description,
            )
            shop_x.save()
            serializer = ShopModelSerializer(shop_x)
            return Response({'code': 200, 'msg': '添加成功', 'data': serializer.data})
        else:
            good.stock -= 1
            shop.stock += 1
            good.save()
            shop.save()
            GoodsSerializer(good)
            serializer = ShopModelSerializer(shop)
            return Response({'code': 200, 'msg': '修改成功', 'data': serializer.data})


# class DetailGoodsAPIView(RetrieveAPIView):
#     queryset = GoodsModel.objects.all()
#     serializer_class = GoodsSerializer
#     lookup_field = 'pk'
class DetailGoodsAPIView(ListAPIView):
    queryset = GoodsModel.objects.all()
    serializer_class = GoodsSerializer

    def get(self, request, *args, **kwargs):
        pk = request.query_params.get('id')
        print(pk)
        goods = GoodsModel.objects.filter(id=pk).first()
        serializer = GoodsSerializer(goods)
        return Response({'msg': '获取成功', 'data': serializer.data})
